package com.hl.redisdemo.controller;

import com.hl.redisdemo.util.RedissonLockUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

/**
 * @author hulei
 * @date 2024/2/6 17:23
 */

@RestController
public class RedisDemoController {

    @GetMapping("/redisTest")
    public String redisTest() throws InterruptedException {
        String str;
        String lockKey = "myLock";
        // 生成唯一请求标识
        String requestId = UUID.randomUUID().toString();
        // 集群场景下，锁超时时间应该保证大于多数节点获取锁的时间
        //当发生在多数节点获取锁的时间大于锁超时时间时，获取到的锁在各节点早已超时失效，锁失效
        int expireTime = 5000; // 锁的过期时间为5秒,注意,
        // 尝试获取锁
        if (RedissonLockUtil.tryLock(lockKey, requestId, expireTime)) {
            System.out.println("获取到锁");
            // 执行业务逻辑
            Thread.sleep(2000);
            // 释放锁
            if (RedissonLockUtil.unlock(lockKey, requestId)) {
                System.out.println("释放锁成功");
                str = "释放锁成功";
            } else {
                System.out.println("释放锁失败");
                str = "释放锁失败";
            }
        } else {
            System.out.println("获取锁失败");
            str = "获取锁失败";
        }
        return str;
    }
}
